import store from '@/store';
import router from '@/router';
import { Message } from 'element-ui';

const whiteList = ['/401', '/404']; // 不重定向白名单

// permissiom judge
export default function hasPermission(routePermissions) {
  const { myPermissions } = store.getters;
  if (!routePermissions) return true;
  const result = myPermissions.some(per => per === '*' || routePermissions.indexOf(per) >= 0);
  return result;
}

function correctRoute(routers, to) {
  const hasRoute = routers.some(route => route.path === to.path);
  if (hasRoute) {
    return to;
  }
  return routers.length ? routers[0] : { path: '/404' };
}

router.beforeEach((to, from, next) => {
  if (store.getters.myPermissions.length === 0) {
    store.dispatch('GetUserInfo').then((res) => {
      store.dispatch('GenerateRoutes', res.data.permissions).then(() => {
        router.addRoutes(store.getters.addRouters);
        const route = router.match(to.path);
        if (route && route.matched && route.matched.length) {
          next();
        } else {
          next(correctRoute(store.getters.addRouters, to));
        }
      });
    }).catch(() => {
      Message({
        type: 'error',
        duration: 5 * 1000,
        message: '验证失败，请重新登录',
      });
    });
  } else if (hasPermission(to.meta.permission)) {
    next();
  } else if (whiteList.indexOf(to.path) !== -1) {
    next();
  } else {
    next({ path: '/401' });
  }
  next();
});
